Skip to content

Conversation

@ajtmccarty
Copy link
Contributor

@ajtmccarty ajtmccarty commented Aug 13, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Improved merge behavior to gracefully handle None values, avoiding unnecessary conflicts when combining settings or data. When one side is None and the other has a value, the non-None value is used. Existing behavior for lists and nested structures remains unchanged.
  • Tests

    • Added test coverage to validate the new None-handling logic during merges.

@coderabbitai
Copy link

coderabbitai bot commented Aug 13, 2025

Walkthrough

Refactors deep_merge_dict in infrahub_sdk/utils.py to use local variables and expand None-handling rules, maintaining dict/list merge behavior. Adds unit tests verifying None-handling per key in tests/unit/sdk/test_utils.py. No public signatures changed.

Changes

Cohort / File(s) Summary
Deep merge behavior update
infrahub_sdk/utils.py
Refactors deep_merge_dict with local a_val/b_val, preserves dict/list recursion, and broadens None-handling: prefer non-None over None, skip when equal or b_val is None, otherwise raise on conflict.
Unit tests for None-handling
tests/unit/sdk/test_utils.py
Adds tests ensuring deep_merge_dict chooses non-None values per key across dicts and keeps existing merge behaviors unchanged.

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant Utils as deep_merge_dict
  Caller->>Utils: deep_merge_dict(dicta, dictb)
  loop for each key in dictb
    alt both values are dict
      Utils->>Utils: recurse deep_merge_dict(a_val, b_val)
    else both values are list
      Utils->>Utils: merge lists ([items in A not in B] + B)
    else a_val is None and b_val not None
      Utils->>Utils: set dicta[key] = b_val
    else values equal or b_val is None
      Utils->>Utils: no change
    else conflict
      Utils->>Caller: raise ValueError
    end
  end
  Utils-->>Caller: merged dicta
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Possibly related PRs

Suggested reviewers

  • ogenstad
  • gmazoyer
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch develop

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary or Summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@codecov
Copy link

codecov bot commented Aug 13, 2025

Codecov Report

❌ Patch coverage is 88.88889% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
infrahub_sdk/utils.py 88.88% 0 Missing and 1 partial ⚠️
@@                 Coverage Diff                  @@
##           infrahub-develop     #496      +/-   ##
====================================================
+ Coverage             76.24%   76.25%   +0.01%     
====================================================
  Files                   100      100              
  Lines                  9032     9036       +4     
  Branches               1731     1732       +1     
====================================================
+ Hits                   6886     6890       +4     
  Misses                 1670     1670              
  Partials                476      476              
Flag Coverage Δ
integration-tests 36.04% <0.00%> (-0.02%) ⬇️
python-3.10 49.30% <88.88%> (+0.02%) ⬆️
python-3.11 49.28% <88.88%> (+<0.01%) ⬆️
python-3.12 48.16% <88.88%> (-1.09%) ⬇️
python-3.13 49.28% <88.88%> (+0.04%) ⬆️
python-3.9 48.00% <88.88%> (+0.02%) ⬆️
python-filler-3.12 24.56% <0.00%> (-0.02%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
infrahub_sdk/utils.py 85.38% <88.88%> (+0.27%) ⬆️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (5)
tests/unit/sdk/test_utils.py (1)

99-104: Optional: expand coverage for edge cases (both None, nested dict with None, and conflicts)

Consider adding a few more assertions to lock in behavior and guard regressions:

  • Both sides None keeps None
  • Nested dict vs None keeps existing nested structure
  • Conflicting non-None scalars raise

For example:

def test_deep_merge_dict_none_additional_cases():
    # both None -> keep None
    assert deep_merge_dict({"k": None}, {"k": None}) == {"k": None}

    # nested dict vs None -> keep existing dict
    a = {"obj": {"sub": 1}}
    b = {"obj": None}
    assert deep_merge_dict(a, b) == {"obj": {"sub": 1}}

    # conflict on non-None scalar -> raises
    with pytest.raises(ValueError):
        deep_merge_dict({"k": "a"}, {"k": "b"})
infrahub_sdk/utils.py (4)

148-157: Optional: short-circuit equality and None-on-right before dict/list handling

A small reordering can avoid unnecessary recursion/list-processing when values are equal or when b_val is None. This keeps behavior identical but saves work in common cases.

Apply within this block:

-            if isinstance(a_val, dict) and isinstance(b_val, dict):
-                deep_merge_dict(a_val, b_val, path + [str(key)])
-            elif isinstance(a_val, list) and isinstance(b_val, list):
-                # Merge lists
-                # Cannot use compare_list because list of dicts won't work (dict not hashable)
-                dicta[key] = [i for i in a_val if i not in b_val] + b_val
-            elif a_val is None and b_val is not None:
-                dicta[key] = b_val
-            elif a_val == b_val or (a_val is not None and b_val is None):
-                continue
+            if a_val == b_val or (a_val is not None and b_val is None):
+                continue
+            elif isinstance(a_val, dict) and isinstance(b_val, dict):
+                deep_merge_dict(a_val, b_val, path + [str(key)])
+            elif isinstance(a_val, list) and isinstance(b_val, list):
+                # Merge lists
+                # Cannot use compare_list because list of dicts won't work (dict not hashable)
+                dicta[key] = [i for i in a_val if i not in b_val] + b_val
+            elif a_val is None and b_val is not None:
+                dicta[key] = b_val
             else:
                 raise ValueError("Conflict at %s" % ".".join(path + [str(key)]))

154-157: None-handling semantics look correct; consider documenting explicitly

Behavior now is:

  • If a is None and b is not None: take b
  • If b is None (and a is not None): keep a
  • If equal: keep a
  • Otherwise, merge dicts/lists or raise conflict

Recommend updating the function docstring to call out in-place merge semantics and the None rules to prevent misuse.

Here’s suggested docstring text (outside the changed lines):

def deep_merge_dict(dicta: dict, dictb: dict, path: list[str] | None = None) -> dict:
    """Deep-merge dictb into dicta, modifying dicta in place and returning it.

    Rules:
    - Dict vs dict: recursively deep-merge.
    - List vs list: keep items unique, preserve order: items from dicta not in dictb, then all items from dictb.
    - None handling (per key):
      * dicta[key] is None and dictb[key] is not None -> take dictb[key].
      * dictb[key] is None (and dicta[key] is not None) -> keep dicta[key].
      * equal values -> keep dicta[key].
    - Any other non-equal, non-None type/value mismatch -> raise ValueError with a path to the conflict.
    """

153-153: FYI: list merge is O(n*m); acceptable, but watch for very large lists

The membership check i not in b_val leads to quadratic behavior. If you expect very large lists of hashables, consider a specialized fast-path (e.g., precompute set_b = set(b_val) when all elements are hashable) and fall back to the current approach for unhashables (dicts).


161-161: Nit: reuse b_val alias for consistency

dicta[key] = dictb[key] can become dicta[key] = b_val to match the alias pattern introduced above.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 760cf3a and 3269a41.

📒 Files selected for processing (2)
  • infrahub_sdk/utils.py (1 hunks)
  • tests/unit/sdk/test_utils.py (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
tests/unit/sdk/test_utils.py (1)
infrahub_sdk/utils.py (1)
  • deep_merge_dict (138-162)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: unit-tests (3.12)
  • GitHub Check: unit-tests (3.13)
  • GitHub Check: unit-tests (3.10)
  • GitHub Check: unit-tests (3.11)
  • GitHub Check: integration-tests-latest-infrahub
  • GitHub Check: unit-tests (3.9)
  • GitHub Check: unit-tests (3.13)
  • GitHub Check: integration-tests-latest-infrahub
🔇 Additional comments (2)
tests/unit/sdk/test_utils.py (1)

99-104: LGTM: Added None-handling test for deep_merge_dict is correct and valuable

This test accurately captures the intended per-key None semantics: None in one dict should not overwrite a non-None in the other, and vice versa.

infrahub_sdk/utils.py (1)

145-147: LGTM: local aliases clarify intent and avoid repeated lookups

Using a_val and b_val improves readability and slightly reduces repeated indexing. No behavior change.

@ajtmccarty ajtmccarty merged commit c1d1bd4 into infrahub-develop Aug 13, 2025
35 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant